﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using vngoodlife.Singleton;
using System.Data.Linq;
using vngoodlife.Util;
using vngoodlife.DTO;
using System.IO;
using System.Text.RegularExpressions;

namespace vngoodlife.Controllers
{
    
    public class ArticleController : Controller
    {
        
        #region BackEnd

        /// <summary>
        /// Article List
        /// </summary>
        /// <returns></returns>
        [CheckMemberVisibility, Authorize(Roles = ConstantClass.articleAuthentication)]
        public ActionResult ArticleList_BackEnd()
        {
            string statusID = "";
            if (Request.Cookies[ConstantClass.cooArticleStatusID] != null && Request.Cookies[ConstantClass.cooArticleStatusID].Value != "")
            {
                statusID = Request.Cookies[ConstantClass.cooArticleStatusID].Value;
            }

            string articleTypeID = "";
            if (Request.Cookies[ConstantClass.cooArticleTypeID] != null && Request.Cookies[ConstantClass.cooArticleTypeID].Value != "")
            {
                articleTypeID = Request.Cookies[ConstantClass.cooArticleTypeID].Value;
            }

            string amount = ConstantClass.defaultAmount;
            if (Request.Cookies[ConstantClass.cooAmount] != null)
            {
                amount = Request.Cookies[ConstantClass.cooAmount].Value;
            }

            //ViewBag.Visiblity = new SelectList(new[] { "1", "0" }
            //                     .Select(x => new { value = x, text = x }), "value", "text", amount);

            ViewBag.ArticleStatusList = new SelectList(DataSingleton.Instance.GetArticleStatusModels()
                                        .GetArticleStatus().ToList(), "ArtStatusID", "ArtStatusName", statusID);

            ViewBag.amountList = new SelectList(new[] { "25", "50", "100", "300", "800" }
                                 .Select(x => new { value = x, text = x }), "value", "text", amount);

            ViewBag.ArticleTypeList = new SelectList(DataSingleton.Instance.GetArticleModels()
                                      .GetArticleType().ToList(), "MenuListID", "MenuName", articleTypeID);
            
            return View("/Views/BackEnd/Article/ArticleList.cshtml",
                        DataSingleton.Instance.GetArticleModels().GetFilterArticle_BackEnd(statusID, articleTypeID, amount));
        }


        [CheckMemberVisibility, Authorize(Roles = ConstantClass.articleAuthentication), HttpPost]
        [ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult DeleteArticle(int articleID)
        {
            DataSingleton.Instance.GetArticleModels().DeleteArticle(articleID, Path.Combine(Request.PhysicalApplicationPath.ToString(),
                            "Content/images/article/thumbnail/"));

            return RedirectToAction("ArticleList_BackEnd", "Article");
        }

      
        /// <summary>
        /// Change Article Status that is visible or invisible
        /// </summary>
        /// <param name="menuListID"></param>
        /// <param name="menuVisible"></param>
        /// <returns></returns>
       // [Authorize(Roles = ConstantClass.autArticle)]
        //public ActionResult ChangeArticleVisible(int articleID, bool articleVisible)
        //{
        //    DataSingleton.Instance.GetArticleModels().ChangeArticleVisible(articleID, articleVisible);
        //    return RedirectToAction("ArticleList_BackEnd", "Article");
        //}


        /// <summary>
        /// use in article list page to filter status of article
        /// </summary>
        /// <param name="articleTypeID"></param>
        /// <returns></returns>
        [CheckMemberVisibility, Authorize]
        public ActionResult ChangeArticleStatus(String articleStatusID)
        {
            if (Request.Cookies[ConstantClass.cooArticleStatusID] == null)
            {
                HttpCookie cookie = new HttpCookie(ConstantClass.cooArticleStatusID, articleStatusID);
                Response.Cookies.Add(cookie);
                cookie.Expires = DateTime.Now.AddHours(ConstantClass.cooArticleStatusIDTimeLife);
            }
            else
            {
                Response.Cookies[ConstantClass.cooArticleStatusID].Expires = DateTime.Now.AddHours(ConstantClass.cooArticleStatusIDTimeLife);
                Response.Cookies[ConstantClass.cooArticleStatusID].Value = articleStatusID;
            }

            return RedirectToAction("ArticleList_BackEnd", "Article");
        }

        /// <summary>
        /// use in article list page to filter type of article
        /// </summary>
        /// <param name="articleTypeID"></param>
        /// <returns></returns>
        [CheckMemberVisibility, Authorize]
        public ActionResult ChangeArticleType(String articleTypeID)
        {
            if (Request.Cookies[ConstantClass.cooArticleTypeID] == null)
            {
                HttpCookie cookie = new HttpCookie(ConstantClass.cooArticleTypeID, articleTypeID);
                Response.Cookies.Add(cookie);
                cookie.Expires = DateTime.Now.AddHours(ConstantClass.cooArticleTypeIDTimeLife);
            }
            else
            {
                Response.Cookies[ConstantClass.cooArticleTypeID].Expires = DateTime.Now.AddHours(ConstantClass.cooArticleTypeIDTimeLife);
                Response.Cookies[ConstantClass.cooArticleTypeID].Value = articleTypeID;
            }

            return RedirectToAction("ArticleList_BackEnd", "Article");
        }

        /// <summary>
        /// in backend, get a specific amount of articles in filter
        /// </summary>
        /// <param name="articleTypeID"></param>
        /// <returns></returns>
        [CheckMemberVisibility, Authorize]
        public ActionResult ChangeAmountToShow(String amount)
        {
            if (Request.Cookies[ConstantClass.cooAmount] == null)
            {
                HttpCookie cookie = new HttpCookie(ConstantClass.cooAmount, amount);
                Response.Cookies.Add(cookie);
                cookie.Expires = DateTime.Now.AddHours(ConstantClass.coodefaultAmountTimeLife);
            }
            else
            {
                Response.Cookies[ConstantClass.cooAmount].Expires = DateTime.Now.AddHours(ConstantClass.coodefaultAmountTimeLife);
                Response.Cookies[ConstantClass.cooAmount].Value = amount;
            }

            return RedirectToAction("ArticleList_BackEnd", "Article");
        }


        [CheckMemberVisibility, Authorize(Roles = ConstantClass.articleAuthentication), ValidateInput(false) ]
        public ActionResult ArticleEdit(int articleID)
        {
            var art = DataSingleton.Instance.GetLinQContext().Articles.Single(u => u.ArticleID == articleID);
            ViewBag.ArticleTypeList = new SelectList(DataSingleton.Instance.GetArticleModels()
                                     .GetArticleType().ToList(), "MenuListID", "MenuName");
            ViewBag.OneArticleTypeList = DataSingleton.Instance.GetLinQContext().TypesOfArticles.Where(u=>u.ArticleID == articleID);

            ViewBag.ArticleStatusList = new SelectList(DataSingleton.Instance.GetArticleStatusModels()
                           .GetArticleStatus().ToList(), "ArtStatusID", "ArtStatusName", art.ArtStatusID);

            ViewBag.OneArticleTagList = DataSingleton.Instance.GetLinQContext().Article_Tags.Where(u => u.ArticleID == articleID);

            ViewBag.RelatedArticle = DataSingleton.Instance.GetLinQContext().Related_Articles.Where(u => u.ArticleID == articleID);
            return View("/Views/Backend/Article/ArticleEdit.cshtml", art);
        }


        //[HttpPost, ValidateInput(false)]
        //[ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        //public ActionResult ArticleEdit(Article art, HttpPostedFileBase uploadFile)
        //{
        //    if (uploadFile != null && uploadFile.ContentLength > 0)
        //    {
        //        //Upload Image article
        //        art.Photo = DataSingleton.Instance.GetGeneralModels().UploadArticleThumbnail(uploadFile, Path.Combine(Request.PhysicalApplicationPath.ToString(),
        //            "Content/images/article/thumbnail/"), art.Photo, art.Title);
        //    }


        //    art.UpdateDate = DateTime.Now;
        //    art.AdminName = "trongthien";
        //    DataSingleton.Instance.GetArticleModels().ArticleEdit(art);

        //    //General_dto.ClearCacheDataContext(DataSingleton.Instance.GetLinQContext());
        //    //DataSingleton.Instance.GetLinQContext().Articles.Attach(arti, true);
        //    //DataSingleton.Instance.GetLinQContext().Refresh(RefreshMode.KeepCurrentValues, arti);
        //    //DataSingleton.Instance.GetLinQContext().Articles.Context.SubmitChanges();

        //    ViewBag.ArticleStatusList = new SelectList(DataSingleton.Instance.GetArticleStatusModels().GetArticleStatus().ToList(), "ArtStatusID", "ArtStatusName", art.ArtStatusID);
        //    return View("/Views/Backend/Article/ArticleEdit.cshtml", art);
        //}


        [CheckMemberVisibility, Authorize(Roles = ConstantClass.articleAuthentication), HttpPost, ValidateInput(false)]
        [ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult ArticleEdit(int articleID, HttpPostedFileBase uploadFile, string artSubjectName)
        {


            General_dto.ClearCacheDataContext(DataSingleton.Instance.GetLinQContext());
            Article art = DataSingleton.Instance.GetLinQContext().Articles.SingleOrDefault(u => u.ArticleID == articleID);
            TryUpdateModel(art);

            //art.ArticleSubject = DataSingleton.Instance.GetLinQContext().ArticleSubjects.Single(u => u.ArtSubjectID == ArtSubjectID);
            if (uploadFile != null && uploadFile.ContentLength > 0 && ModelState.IsValid)
            {
                //Upload Image article
                art.Photo = DataSingleton.Instance.GetGeneralModels()
                            .UploadArticleThumbnail(uploadFile, Path.Combine(Request.PhysicalApplicationPath.ToString(),
                            "Content/images/article/thumbnail/"), art.Photo, art.Title);
            }
            if(artSubjectName.Trim() == "" || art.ArtSubjectID ==0)
            {
                art.ArtSubjectID = null;
            }
            
            //art.AdminName = HttpContext.User.Identity.Name;

            if (ModelState.IsValid && DataSingleton.Instance.GetArticleModels().ArticleEdit(art, HttpContext.User.Identity.Name))
            {
                ModelState.Clear();
                    ModelState.AddModelError("Notice", "Thông tin đã được cập nhật.");
            }
            else
            {
                ModelState.AddModelError("Notice", "Có lỗi khi cập nhật thông tin.");
            }

            ViewBag.ArticleTypeList = new SelectList(DataSingleton.Instance.GetArticleModels()
                                     .GetArticleType().ToList(), "MenuListID", "MenuName");
            ViewBag.OneArticleTypeList = DataSingleton.Instance.GetLinQContext()
                                       .TypesOfArticles.Where(u => u.ArticleID == articleID);
            ViewBag.ArticleStatusList = new SelectList(DataSingleton.Instance.GetArticleStatusModels()
                                       .GetArticleStatus().ToList(), "ArtStatusID", "ArtStatusName", art.ArtStatusID);
            ViewBag.OneArticleTagList = DataSingleton.Instance.GetLinQContext().Article_Tags.Where(u => u.ArticleID == articleID);

            ViewBag.RelatedArticle = DataSingleton.Instance.GetLinQContext().Related_Articles.Where(u => u.ArticleID == articleID);

            return View("/Views/Backend/Article/ArticleEdit.cshtml", art);
        }

        /// <summary>
        /// delete the types of one article, use in article edit,ajax
        /// </summary>
        /// <param name="articleID"></param>
        /// <returns></returns>
        [CheckMemberVisibility, Authorize(Roles = ConstantClass.articleAuthentication)]
        public PartialViewResult DeleteTypeOfOneArticle(int articleID, int articleTypeID)
        {
            DataSingleton.Instance.GetTypesOfArticleModels().DeleteTypesOfArticle(articleTypeID, articleID);

            ViewBag.artid = articleID;// pass ID to partial view
            var types = DataSingleton.Instance.GetLinQContext().TypesOfArticles.Where(u => u.ArticleID == articleID);
            return PartialView("/Views/Backend/Article/_ArticleEdit_Category.cshtml", types);
        }


        [CheckMemberVisibility, Authorize(Roles = ConstantClass.articleAuthentication)]
        public PartialViewResult SetTypeIntoArticle( int articleID, string articleTypeIDs = "")
        {
            if (articleTypeIDs != "")
            {
                DataSingleton.Instance.GetTypesOfArticleModels().InsertManyType(articleID, articleTypeIDs);
            }
            ViewBag.artid = articleID;// pass ID to partial view
            var types = DataSingleton.Instance.GetLinQContext().TypesOfArticles.Where(u => u.ArticleID == articleID);
            return PartialView("/Views/Backend/Article/_ArticleEdit_Category.cshtml", types);
        }
        /// <summary>
        /// set a type into article, ajax
        /// </summary>
        /// <param name="articleTypeID"></param>
        /// <param name="artid"></param>
        /// <returns></returns>
        //public PartialViewResult SetTypeIntoArticle(int articleTypeID, int articleID)
        //{
        //    TypesOfArticle ty = new TypesOfArticle { ArticleID = articleID, ArticleTypeID = articleTypeID };
        //    DataSingleton.Instance.GetTypesOfArticleModels().InsertType(ty);
            
        //    Thread.Sleep(2000);
        //    ViewBag.artid = articleID;// pass ID to partial view
        //    var types = DataSingleton.Instance.GetLinQContext().TypesOfArticles.Where(u => u.ArticleID == articleID);
        //    return PartialView("/Views/Backend/Article/_ArticleEdit_Category.cshtml", types);
        //}


        [CheckMemberVisibility, Authorize(Roles = ConstantClass.articleAuthentication)]
        public PartialViewResult SetRelatedArticle( int articleID,int relatedArticleID = 0)
        {
            if (relatedArticleID != 0)
            {
                Related_Article related = new Related_Article { ArticleID = articleID, RelatedArticleID = relatedArticleID };
                DataSingleton.Instance.GetRelatedArticleModels().InsertRelatedArticle(related);
            }
            ViewBag.artid = articleID;// pass ID to partial view


            var relateds = DataSingleton.Instance.GetLinQContext().Related_Articles
                                     .Where(u =>
                                     (u.ArticleID == articleID && u.RelatedArticle.ArticleVisible == true
                                            && (u.RelatedArticle.ArtStatusID == 3 || u.RelatedArticle.ArtStatusID == 4))
                                  || (u.RelatedArticleID == articleID && u.Article.ArticleVisible == true
                                            && (u.Article.ArtStatusID == 3 || u.Article.ArtStatusID == 4))
                                           )
                                           .OrderByDescending(u => u.ArticleID);

          //  var relateds = DataSingleton.Instance.GetLinQContext().Related_Articles.Where(u => u.ArticleID == articleID);
            return PartialView("/Views/Backend/Article/_ArticleEdit_RelatedArticle.cshtml", relateds);
        }


        /// <summary>
        /// delete the tags of one article, use in article edit, ajax
        /// </summary>
        /// <param name="articleID"></param>
        /// <returns></returns>
        [CheckMemberVisibility, Authorize(Roles = ConstantClass.articleAuthentication)]
        public PartialViewResult DeleteTagOfArticle(int articleID, int articleTagID)
        {
            DataSingleton.Instance.GetArticleTagModels().DeleteTagOfArticle(articleTagID, articleID);
            
            ViewBag.artid = articleID;// pass ID to partial view
            var tags = DataSingleton.Instance.GetLinQContext().Article_Tags.Where(u => u.ArticleID == articleID);
            return PartialView("/Views/Backend/Article/_ArticleEdit_Tags.cshtml", tags);
        }


        /// <summary>
        /// delete the related of one article, use in article edit, ajax
        /// </summary>
        /// <param name="articleID"></param>
        /// <returns></returns>
        [CheckMemberVisibility, Authorize(Roles = ConstantClass.articleAuthentication)]
        public PartialViewResult DeleteRelatedArticle(int articleID, int relatedArticleID)
        {
            DataSingleton.Instance.GetRelatedArticleModels().DeleteRelatedArticle(articleID, relatedArticleID);

            ViewBag.artid = articleID;// pass ID to partial view

            var related = DataSingleton.Instance.GetLinQContext().Related_Articles
                                     .Where(u =>
                                     (u.ArticleID == articleID && u.RelatedArticle.ArticleVisible == true
                                            && (u.RelatedArticle.ArtStatusID == 3 || u.RelatedArticle.ArtStatusID == 4))
                                  || (u.RelatedArticleID == articleID && u.Article.ArticleVisible == true
                                            && (u.Article.ArtStatusID == 3 || u.Article.ArtStatusID == 4))
                                           )
                                           .OrderByDescending(u => u.ArticleID);

         //   var related = DataSingleton.Instance.GetLinQContext().Related_Articles.Where(u => u.ArticleID == articleID);
            return PartialView("/Views/Backend/Article/_ArticleEdit_RelatedArticle.cshtml", related);
        }


        [CheckMemberVisibility, Authorize(Roles = ConstantClass.articleAuthentication)]
        public PartialViewResult SetTagsIntoArticle( int artID,string tagID = "")
        {
            if (tagID != "")
            {
                DataSingleton.Instance.GetArticleTagModels().InsertManyTag(artID, tagID);
            }
            ViewBag.artid = artID;// pass ID to partial view
            var tags = DataSingleton.Instance.GetLinQContext().Article_Tags.Where(u => u.ArticleID == artID);
            return PartialView("/Views/Backend/Article/_ArticleEdit_Tags.cshtml", tags);
        }
        /// <summary>
        /// set a tags into article, ajax
        /// </summary>
        /// <param name="articleTypeID"></param>
        /// <param name="artid"></param>
        /// <returns></returns>
        //public PartialViewResult SetTagsIntoArticle(int tagID, int artID)
        //{
        //    Article_Tag artTag = new Article_Tag { ArticleID = artID, TagsID = tagID };
        //    if (tagID != 0)
        //    {
        //        DataSingleton.Instance.GetArticleTagModels().InsertTag(artTag);
        //    }
        //    Thread.Sleep(2000);
        //    ViewBag.artid = artID;// pass ID to partial view
        //    var tags = DataSingleton.Instance.GetLinQContext().Article_Tags.Where(u => u.ArticleID == artID);
        //    return PartialView("/Views/Backend/Article/_ArticleEdit_Tags.cshtml", tags);
        //}

        [CheckMemberVisibility, ValidateInput(false), Authorize(Roles = ConstantClass.articleAuthentication)]
        public ActionResult ArticleCreate()
        {

            ViewBag.ArticleTypeList = new SelectList(DataSingleton.Instance.GetArticleModels()
                                     .GetArticleType().ToList(), "MenuListID", "MenuName");

            ViewBag.ArticleStatusList = new SelectList(DataSingleton.Instance.GetArticleStatusModels()
                           .GetArticleStatus().ToList(), "ArtStatusID", "ArtStatusName",3);

            return View("/Views/Backend/Article/ArticleCreate.cshtml");
        }


        [CheckMemberVisibility, Authorize(Roles = ConstantClass.articleAuthentication), HttpPost, ValidateInput(false)]
        [ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult ArticleCreate(Article art, HttpPostedFileBase uploadFile, string artSubjectName,
                                          string tagIDs, string articleTypeIDs, string relatedArticleID)
        {
            ViewBag.ArticleTypeList = new SelectList(DataSingleton.Instance.GetArticleModels()
                                     .GetArticleType().ToList(), "MenuListID", "MenuName");
            ViewBag.ArticleStatusList = new SelectList(DataSingleton.Instance.GetArticleStatusModels()
                           .GetArticleStatus().ToList(), "ArtStatusID", "ArtStatusName", 3);
            TryUpdateModel(art);
            if (uploadFile != null && uploadFile.ContentLength > 0 && art.Title.ToString() != "" && ModelState.IsValid)
            {
                //Upload Image article
                art.Photo = DataSingleton.Instance.GetGeneralModels()
                            .UploadArticleThumbnail(uploadFile, Path.Combine(Request.PhysicalApplicationPath.ToString(),
                            "Content/images/article/thumbnail/"), art.Photo, art.Title);
            }
            if (artSubjectName.Trim() == "" || art.ArtSubjectID == 0)
            {
                art.ArtSubjectID = null;
            }


            if (articleTypeIDs == "0")
            {
                ModelState.AddModelError("NoticePage", "Nhập loại cho bài viết");
                return View("/Views/Backend/Article/ArticleCreate.cshtml");
            }

            if (ModelState.IsValid)
            {
                int id = DataSingleton.Instance.GetArticleModels().ArticleCreate(art, HttpContext.User.Identity.Name, null);
                if (id != 0)
                {
                    if (tagIDs != "0")
                    {
                        DataSingleton.Instance.GetArticleTagModels().InsertManyTag(id, tagIDs);
                    }
                    if (articleTypeIDs != "0")
                    {
                        DataSingleton.Instance.GetTypesOfArticleModels().InsertManyType(id, articleTypeIDs);
                    }
                    

                    if (relatedArticleID != "0")
                    {
                        DataSingleton.Instance.GetRelatedArticleModels().InsertManyRelatedArticle(id, relatedArticleID);
                    }
                }
            }

            //if (ModelState.IsValid && id != 0)
            //{
            //    ModelState.Clear();
            //    ModelState.AddModelError("Notice", "Thông tin đã được cập nhật.");
            //}
            //else
            //{
            //    ModelState.AddModelError("Notice", "Có lỗi khi cập nhật thông tin.");
            //}

            

           
            return RedirectToAction("ArticleCreate", "Article");
        }


        /// <summary>
        /// use in page ArticleEdit to autocomplete in field related article. Ajax
        /// </summary>
        /// <param name="term"></param>
        /// <returns></returns>
        [CheckMemberVisibility, Authorize]
        public ActionResult GetArticleName(string term, int articleID)
        {
            term = term.Trim();
          //  term = term.Replace(" ", "");
            if (term.Length > 1)
            {
                int op = term.LastIndexOf(",");
                term = term.Substring(op + 1);
            }
            term = term.Trim();
            if (articleID == 0)//use in article create
            {
                var ArticleName = DataSingleton.Instance.GetLinQContext().Articles
                                 .Where(u => u.Title.Contains(term))
                                 .OrderByDescending(u=>u.ArticleID)
                                 .Take(10)
                                 .Select(u => new { label = u.Title, id = u.ArticleID });
                if (ArticleName.Count() == 0)
                {
                    IEnumerable<Article> tags = new Article[] { new Article { ArticleID = 0, Title = "Tag này chưa có" } };
                    var aa = tags.Select(u => new { label = u.Title, id = u.ArticleID });
                    return Json(aa.ToArray(), JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(ArticleName.ToArray(), JsonRequestBehavior.AllowGet);
                }
            }
            else //use in article edit, get article that the current article doesn't have.
            {
                IQueryable<int> relatedArticleIDs = DataSingleton.Instance.GetLinQContext().Related_Articles
                                      .Where(u => u.ArticleID == articleID).Select(u=>u.RelatedArticleID);

                var relatedArticleName = DataSingleton.Instance.GetLinQContext().Articles
                                 .Where(u => u.Title.Contains(term) 
                                             && !relatedArticleIDs.Contains(u.ArticleID) 
                                             && u.ArticleID != articleID)
                                 .OrderByDescending(u => u.ArticleID)
                                 .Take(10)
                                 .Select(u => new { label = u.Title, id = u.ArticleID });
                if (relatedArticleName.Count() == 0)
                {
                    IEnumerable<Article> tags = new Article[] { new Article { ArticleID = 0, Title = "Bài này chưa có hoặc thêm rồi" } };
                    var aa = tags.Select(u => new { label = u.Title, id = u.ArticleID });
                    return Json(aa.ToArray(), JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(relatedArticleName.ToArray(), JsonRequestBehavior.AllowGet);
                }
            }

            //return Json(artTagName.ToArray(), JsonRequestBehavior.AllowGet);
        }


        [CheckMemberVisibility, Authorize]
        public PartialViewResult AdvanceSearch(string keySearch)
        {
            IQueryable<Article> result = null;
            if (keySearch != "")
            {
                result = DataSingleton.Instance.GetLinQContext().Articles.Where(u => u.Title.Contains(keySearch))
                                      .OrderByDescending(u=>u.ArticleID);
            }

            return PartialView("/Views/Backend/Article/_ArticleList_SearchResult.cshtml", result);
        }


        [CheckMemberVisibility, Authorize]
        public PartialViewResult AdvanceSearch2(int subjectID)
        {
            IQueryable<Article> result = null;
            if (subjectID != 0)
            {
                result = DataSingleton.Instance.GetLinQContext().Articles.Where(u => u.ArtSubjectID == subjectID)
                                      .OrderByDescending(u=>u.ArticleID);
            }

            return PartialView("/Views/Backend/Article/_ArticleList_SearchResult.cshtml", result);
        }


        ///// <summary>
        ///// use in backend , articleList but link to frontend for admin to check quickly and convenient
        ///// </summary>
        ///// <param name="articleSEO_URL"></param>
        ///// <returns></returns>
        //public ActionResult ArticleDetailsFrontend2(int articleID)
        //{
        //    return Redirect("/Cuoc-Song/" + DataSingleton.Instance.GetLinQContext().Articles
        //                                    .SingleOrDefault(u => u.ArticleID == articleID).ArticleSeoUrl);
        //}

        [ChildActionOnly, CheckMemberVisibility, Authorize]
        public ActionResult BuildArticleType_DropdownList(string id,string textTargetID="", string valueTargetID="")
        {
            if (Request.Cookies[ConstantClass.cooArticleTypeID] != null && Request.Cookies[ConstantClass.cooArticleTypeID].Value != "")
            {
                ViewBag.CurrentArticleTypeID = Convert.ToInt16(Request.Cookies[ConstantClass.cooArticleTypeID].Value);
            }
            else
            {
                ViewBag.CurrentArticleTypeID = 0;
            }

            ViewBag.id = id;
            ViewBag.textTargetID = textTargetID;
            ViewBag.valueTargetID = valueTargetID;
            return PartialView("/Views/Backend/Article/_CustomArticleTypeDropDownList.cshtml", 
                               DataSingleton.Instance.GetArticleModels().GetArticleType());
        }


        #endregion

/////////////////////////////////////////////////////////////////////////////////////////////////////

        #region FrontEnd

        
        
        [ChildActionOnly]
        public ActionResult GetOtherArticle(int currentArticleID, int articleTypeID = 101)
        {
            return PartialView("/Views/FrontEnd/Article/_otherNews.cshtml"
                , DataSingleton.Instance.GetArticleModels().GetLatestArticlesByType_Frontend(articleTypeID, 6, currentArticleID));
        }

        [ChildActionOnly]
        [OutputCache(Duration = ConstantClass._FunnyArticleCachingTime)]
        public ActionResult GetFunnyArticle()
        {
            return PartialView("/Views/Shared/FrontEnd/StoryFunny.cshtml", 
                   DataSingleton.Instance.GetArticleModels().GetLatestArticlesByType_Frontend(138,5,0));
        }

        [ChildActionOnly]
        [OutputCache(Duration = ConstantClass._ExtraArticleCachingTime, VaryByParam = "*")]
        public ActionResult GetArticle(string flag)
        {
            IEnumerable<Article> carrier = null;
            if (flag == "1")
            {
                ViewBag.header = "Xem nhiều nhất";
                carrier = DataSingleton.Instance.GetArticleModels().GetMostviewedArticles_Frontend(5, 15);
            }
            else if (flag == "2")
            {
                ViewBag.header = "Bài viết gần đây";
                carrier = DataSingleton.Instance.GetArticleModels().GetRecentArticles_Frontend(5, 30);
            } 
            else 
            {
                ViewBag.header = "Bài viết ngẫu nhiên";
                carrier = DataSingleton.Instance.GetArticleModels().RandomArticles_Frontend(5);
            }
            return PartialView("/Views/FrontEnd/Article/_Article.cshtml", carrier);
        }



        public ActionResult GetArticleByTags_Frontend(string tagsSeoUrl, string currentPage = "1")
        {
            Tag tag = DataSingleton.Instance.GetTagsModels().GetTagByTagSeoUrl(tagsSeoUrl);

            if (tag == null)
            {
                return RedirectToAction("Index", "Home");
            }


            
            ////////////////////////// start paging
            // bar la so luong button link trang trong phan paging vd bar = 7: se co 7 button link den cac tang tuong ung.
            // haftBar = bar/2 +1 : la so luong button link moi ben button link cua currentPage.vd 3 4 [5] 6 7 => haftBar =2.
            int currentPageIndex = 1;
            int totalRows = DataSingleton.Instance.GetArticleModels().Frontend_GetTotalArticleByTags(tag.TagsID);
            int totalPages = (int)Math.Ceiling((double)totalRows / (double)ConstantClass.ArticleResultPageStep);
            //ktra string currentPage co phai là số hay ko
            Match match = Regex.Match(currentPage, @"([0-9])$", RegexOptions.IgnoreCase);
            if (match.Success && currentPage.Length <= 4)
            {
                currentPageIndex = Convert.ToInt16(currentPage);
                if (currentPageIndex > totalPages)//ktra so index trang nhap vao co lon hon tong so trang hay ko
                {
                    currentPageIndex = 1;
                }
            }

            // neu currentpageIndex nam trong nhung so dau(1,2,3..) thi  bar(so page) tren trang  frontend articlelist ko nhay khi
            // bam link co gia tri currentPage tien ve 1

            // case : totalPages nho hoac bang bar thi bar ko ton tai.
            if (totalPages <= ConstantClass.ArticleResultBarStep)
            {
                ViewBag.BeginPage = 1;
                ViewBag.EndPage = totalPages;
            }
//attention://from here: totalPages > bar, bar xuat hien, 
            //case: trang hien tai vao khoang 1 -> halfbar. dau chuoi so.
            else if (currentPageIndex <= ConstantClass.ArticleResultBarStep / 2 + 1)
            {
                // la dang bar dau tien, chua di chuyen.
                ViewBag.BeginPage = 1;
                ViewBag.EndPage = ConstantClass.ArticleResultBarStep;
            }
            //case: trang hien tai vao khoang (totalPages - bar) -> totalPages. cuoi chuoi so.
            else if (currentPageIndex > totalPages - ConstantClass.ArticleResultBarStep)
            {
                // la dang bar cuoi,ko di chuyen toi dc nua.
                ViewBag.BeginPage = totalPages - ConstantClass.ArticleResultBarStep;
                ViewBag.EndPage = totalPages;
            }
            else
            {
                ViewBag.BeginPage = currentPageIndex - ConstantClass.ArticleResultBarStep / 2;
                ViewBag.EndPage = currentPageIndex + ConstantClass.ArticleResultBarStep / 2;
            }

            // kiem tra navi button(paging) khi trang hien tai lon hon halfbar tuc là bar bat dau di chuyen.
            if (currentPageIndex > ConstantClass.ArticleResultBarStep / 2 + 1)
            {
                ViewBag.Previous_Mark_Visibility = true;
            }
            else
            {
                ViewBag.Previous_Mark_Visibility = false;
            }

            if (currentPageIndex <= totalPages - (ConstantClass.ArticleResultBarStep / 2 + 1) && ViewBag.EndPage != totalPages)
            {
                ViewBag.Next_Mark_Visibility = true;
            }
            else
            {
                ViewBag.Next_Mark_Visibility = false;
            }

            if (totalPages <= ConstantClass.ArticleResultBarStep)
            {
                ViewBag.Previous_Mark_Visibility = false;
                ViewBag.Next_Mark_Visibility = false;
            }

            ViewBag.NextPageIndex = Convert.ToInt16(currentPageIndex) + 1;
            ViewBag.PreviousPageIndex = Convert.ToInt16(currentPageIndex) - 1;
            ViewBag.CurrentPage = currentPageIndex;
            ViewBag.LastPage = totalPages;
            ////////////////////////// end paging
            ViewBag.ResultType = "tag";
            ViewBag.HeaderName = "Tags: "+DataSingleton.Instance.GetLinQContext().Tags.Single(u => u.TagsID == tag.TagsID).TagName;

            ViewBag.Title = tag.TagName;
            ViewBag.TagSeoUrl = tagsSeoUrl;
            ViewBag.MetaKeywords = tagsSeoUrl;

            return View("/Views/FrontEnd/Article/ArticleResult.cshtml",
            DataSingleton.Instance.GetArticleModels().GetArticlesByTag_Frontend(tag.TagsID, currentPageIndex, ConstantClass.ArticleResultPageStep));
        }

        public ActionResult GetArticleBySubject_Frontend(string subjectSeoUrl, string currentPage = "1")
        {

            ArticleSubject artSubject = DataSingleton.Instance.GetArticleSubjectModels().GetArticleSubjectBySubjectSeoUrl(subjectSeoUrl);

            //Goto homepage if subjectSeoUrl is not exist
            if (artSubject == null)
            {
                return RedirectToAction("Index", "Home");
            }

            ViewBag.SubjectSeoUrl = subjectSeoUrl;
            ////////////////////////// start paging
            // bar la so luong button link trang trong phan paging vd bar = 7: se co 7 button link den cac tang tuong ung.
            // haftBar = bar/2 +1 : la so luong button link moi ben button link cua currentPage.vd 3 4 [5] 6 7 => haftBar =2.
            int currentPageIndex = 1;
            int totalRows = DataSingleton.Instance.GetArticleModels().Frontend_GetTotalArticleBySubjects(artSubject.ArtSubjectID);
            int totalPages = (int)Math.Ceiling((double)totalRows / (double)ConstantClass.ArticleResultPageStep);
            //ktra string currentPage co phai là số hay ko
            Match match = Regex.Match(currentPage, @"([0-9])$", RegexOptions.IgnoreCase);
            if (match.Success && currentPage.Length <= 4)
            {
                currentPageIndex = Convert.ToInt16(currentPage);
                if (currentPageIndex > totalPages)//ktra so index trang nhap vao co lon hon tong so trang hay ko
                {
                    currentPageIndex = 1;
                }
            }

            // neu currentpageIndex nam trong nhung so dau(1,2,3..) thi  bar(so page) tren trang  frontend articlelist ko nhay khi
            // bam link co gia tri currentPage tien ve 1

            // case : totalPages nho hoac bang bar thi bar ko ton tai.
            if (totalPages <= ConstantClass.ArticleResultBarStep)
            {
                ViewBag.BeginPage = 1;
                ViewBag.EndPage = totalPages;
            }
            //attention://from here: totalPages > bar, bar xuat hien, 
            //case: trang hien tai vao khoang 1 -> halfbar. dau chuoi so.
            else if (currentPageIndex <= ConstantClass.ArticleResultBarStep / 2 + 1)
            {
                // la dang bar dau tien, chua di chuyen.
                ViewBag.BeginPage = 1;
                ViewBag.EndPage = ConstantClass.ArticleResultBarStep;
            }
            //case: trang hien tai vao khoang (totalPages - bar) -> totalPages. cuoi chuoi so.
            else if (currentPageIndex > totalPages - ConstantClass.ArticleResultBarStep)
            {
                // la dang bar cuoi,ko di chuyen toi dc nua.
                ViewBag.BeginPage = totalPages - ConstantClass.ArticleResultBarStep;
                ViewBag.EndPage = totalPages;
            }
            else
            {
                ViewBag.BeginPage = currentPageIndex - ConstantClass.ArticleResultBarStep / 2;
                ViewBag.EndPage = currentPageIndex + ConstantClass.ArticleResultBarStep / 2;
            }

            // kiem tra navi button(paging) khi trang hien tai lon hon halfbar tuc là bar bat dau di chuyen.
            if (currentPageIndex > ConstantClass.ArticleResultBarStep / 2 + 1)
            {
                ViewBag.Previous_Mark_Visibility = true;
            }
            else
            {
                ViewBag.Previous_Mark_Visibility = false;
            }

            if (currentPageIndex <= totalPages - (ConstantClass.ArticleResultBarStep / 2 + 1) && ViewBag.EndPage != totalPages)
            {
                ViewBag.Next_Mark_Visibility = true;
            }
            else
            {
                ViewBag.Next_Mark_Visibility = false;
            }

            if (totalPages <= ConstantClass.ArticleResultBarStep)
            {
                ViewBag.Previous_Mark_Visibility = false;
                ViewBag.Next_Mark_Visibility = false;
            }

            ViewBag.NextPageIndex = Convert.ToInt16(currentPageIndex) + 1;
            ViewBag.PreviousPageIndex = Convert.ToInt16(currentPageIndex) - 1;
            ViewBag.CurrentPage = currentPageIndex;
            ViewBag.LastPage = totalPages;
            ////////////////////////// end paging
            ViewBag.ResultType = "sub";
            ViewBag.HeaderName = "Kỳ: " + DataSingleton.Instance.GetLinQContext().ArticleSubjects.Single(u => u.ArtSubjectID == artSubject.ArtSubjectID).ArtSubjectName;

            ViewBag.MetaKeywords = artSubject.ArtSubjectSeoUrl;
            ViewBag.Title = artSubject.ArtSubjectName;

            return View("/Views/FrontEnd/Article/ArticleResult.cshtml",
            DataSingleton.Instance.GetArticleModels().GetArticlesBySubject_Frontend(artSubject.ArtSubjectID, currentPageIndex, ConstantClass.ArticleResultPageStep));
        }

       // [OutputCache(Duration = ConstantClass._ArticleCachingTime, VaryByParam = "menuSeoUrl")]
        public ActionResult ArticleListFrontend(string menuSeoUrl, string currentPage = "1")
        {
            //int menuListID = DataSingleton.Instance.GetMenuListModels().GetArticleTypeIDFromSeoUrl(menuSeoUrl);
            ViewBag.MenuSeoUrl = menuSeoUrl;
            ViewBag.CurrentPage = currentPage;

            MenuList menu = DataSingleton.Instance.GetLinQContext().MenuLists
                                     .Single(u => u.MenuSeoUrl == menuSeoUrl);

            ViewBag.Title = menu.MenuTitle;
            ViewBag.MetaDescription = menu.MenuDescription;


            return View("/Views/FrontEnd/Article/ArticleList.cshtml");
        }

        [ChildActionOnly]
        [OutputCache(Duration = ConstantClass._ArticleCachingTime, VaryByParam = "*")]
        public ActionResult BuildArticleListFrontendContent(string menuSeoUrl, string currentPage = "1")
        {

            int menuListID = DataSingleton.Instance.GetMenuListModels().GetArticleTypeIDFromSeoUrl(menuSeoUrl);

            ////////////////////////// start paging
            // bar la so luong button link trang trong phan paging vd bar = 7: se co 7 button link den cac tang tuong ung.
            // haftBar = bar/2 +1 : la so luong button link moi ben button link cua currentPage.vd 3 4 [5] 6 7 => haftBar =2.
            int currentPageIndex = 1;
            int totalRows = DataSingleton.Instance.GetArticleModels().Frontend_GetTotalArticleByType(menuListID);
            int totalPages = (int)Math.Ceiling((double)totalRows / (double)ConstantClass.ArticlePageStep);
            //ktra string currentPage co phai là số hay ko
            Match match = Regex.Match(currentPage, @"([0-9])$", RegexOptions.IgnoreCase);
            if (match.Success && currentPage.Length <= 4)
            {
                currentPageIndex = Convert.ToInt16(currentPage);
                if (currentPageIndex > totalPages)//ktra so index trang nhap vao co lon hon tong so trang hay ko
                {
                    currentPageIndex = 1;
                }
            }

            // neu currentpageIndex nam trong nhung so dau(1,2,3..) thi  bar(so page) tren trang  frontend articlelist ko nhay khi
            // bam link co gia tri currentPage tien ve 1

            // case : totalPages nho hoac bang bar thi bar ko ton tai.
            if (totalPages <= ConstantClass.ArticleBarStep)
            {
                ViewBag.BeginPage = 1;
                ViewBag.EndPage = totalPages;
            }
            //attention://from here: totalPages > bar, bar xuat hien, 
            //case: trang hien tai vao khoang 1 -> halfbar. dau chuoi so.
            else if (currentPageIndex <= ConstantClass.ArticleBarStep / 2 + 1)
            {
                // la dang bar dau tien, chua di chuyen.
                ViewBag.BeginPage = 1;
                ViewBag.EndPage = ConstantClass.ArticleBarStep;
            }
            //case: trang hien tai vao khoang (totalPages - bar) -> totalPages. cuoi chuoi so.
            else if (currentPageIndex > totalPages - ConstantClass.ArticleBarStep)
            {
                // la dang bar cuoi,ko di chuyen toi dc nua.
                ViewBag.BeginPage = totalPages - ConstantClass.ArticleBarStep;
                ViewBag.EndPage = totalPages;
            }
            else
            {
                ViewBag.BeginPage = currentPageIndex - ConstantClass.ArticleBarStep / 2;
                ViewBag.EndPage = currentPageIndex + ConstantClass.ArticleBarStep / 2;
            }

            // kiem tra navi button
            if (currentPageIndex > ConstantClass.ArticleBarStep / 2 + 1)
            {
                ViewBag.Previous_Mark_Visibility = true;
            }
            else
            {
                ViewBag.Previous_Mark_Visibility = false;
            }

            if (currentPageIndex <= totalPages - (ConstantClass.ArticleBarStep / 2 + 1) && ViewBag.EndPage != totalPages)
            {
                ViewBag.Next_Mark_Visibility = true;
            }
            else
            {
                ViewBag.Next_Mark_Visibility = false;
            }

            if (totalPages <= ConstantClass.ArticleBarStep)
            {
                ViewBag.Previous_Mark_Visibility = false;
                ViewBag.Next_Mark_Visibility = false;
            }

            ViewBag.NextPageIndex = Convert.ToInt16(currentPageIndex) + 1;
            ViewBag.PreviousPageIndex = Convert.ToInt16(currentPageIndex) - 1;
            ViewBag.CurrentPage = currentPageIndex;
            ViewBag.LastPage = totalPages;
            ////////////////////////// end paging

            ViewBag.ArticleTypeID = menuListID;
            ViewBag.MenuSeoUrl = menuSeoUrl;
            //ViewBag.ArticleTypeName = DataSingleton.Instance.GetLinQContext().MenuLists
            //                         .Single(u => u.MenuListID == menuListID).MenuName;
            return PartialView("/Views/FrontEnd/Article/_ArticleList.cshtml",
                DataSingleton.Instance.GetArticleModels().GetArticlesByType_Frontend(menuListID, currentPageIndex, ConstantClass.ArticlePageStep));
        }



        [ChildActionOnly]
        [OutputCache(Duration = ConstantClass._ArticleCachingTime, VaryByParam = "articleID")]
        public ActionResult BuildArticleContent(int articleID)
        {
            ViewBag.ArticleTypeID = DataSingleton.Instance.GetArticleModels().GetArticleTypeOfArticle(articleID);
            ViewBag.OneArticleTagList = DataSingleton.Instance.GetLinQContext().Article_Tags.Where(u => u.ArticleID == articleID);

            ViewBag.RelatedArticle = DataSingleton.Instance.GetLinQContext().Related_Articles
                                     .Where(u =>
                                     (u.ArticleID == articleID && u.RelatedArticle.ArticleVisible == true
                                            && (u.RelatedArticle.ArtStatusID == 3 || u.RelatedArticle.ArtStatusID == 4))
                                  || (u.RelatedArticleID == articleID && u.Article.ArticleVisible == true 
                                            && (u.Article.ArtStatusID == 3 || u.Article.ArtStatusID == 4))
                                           )
                                           .OrderByDescending(u => u.ArticleID).Take(10);

            var currentArticle = DataSingleton.Instance.GetLinQContext().Articles
                                 .Single(u => u.ArticleID == articleID && u.ArticleVisible == true);

            ViewBag.SubjectArticle = DataSingleton.Instance.GetLinQContext().Articles
                       .Where(u => u.ArtSubjectID == currentArticle.ArtSubjectID 
                                && u.ArticleID != currentArticle.ArticleID && u.ArticleVisible == true 
                                && (u.ArtStatusID == 3 || u.ArtStatusID == 4 ));

            //DataSingleton.Instance.GetArticleModels().GainViewNumber(articleID);
            return PartialView("/Views/FrontEnd/Article/_ArticleContent.cshtml", currentArticle);
        }

        public ActionResult ArticleDetails(string articleSeoUrl, string currentPage = "1")
        {
            var currentArticle = DataSingleton.Instance.GetLinQContext().Articles
                           .SingleOrDefault(u => u.ArticleSeoUrl == articleSeoUrl && u.ArticleVisible == true);
            if (currentArticle == null || currentArticle.ArtStatusID == 1 || currentArticle.ArtStatusID == 2)
            {
                return RedirectToAction("Index","Home");
            }

            int articleID = currentArticle.ArticleID;
            DataSingleton.Instance.GetArticleModels().GainViewNumber(articleID);
            ////////////////////////// start paging comment

            int currentPageIndex = 1;

            int totalRows = DataSingleton.Instance.GetCommentModels().GetTotalCommentIn_Frontend(articleID);
            int totalPages = (int)Math.Ceiling((double)totalRows / (double)ConstantClass.CommentPageStep);

            //ktra string currentPage co phai là số hay ko
            Match match = Regex.Match(currentPage, @"([0-9])$", RegexOptions.IgnoreCase);
            if (match.Success && currentPage.Length <= 4)
            {
                currentPageIndex = Convert.ToInt16(currentPage);
                if (currentPageIndex > totalPages)//ktra so index trang nhap vao co lon hon tong so trang hay ko
                {
                    currentPageIndex = 1;
                }
            }

            // neu currentpageIndex nam trong nhung so dau(1,2,3..) thi  bar(so page) tren trang  frontend articlelist ko nhay khi
            // bam link co gia tri currentPage tien ve 1

            // case : totalPages nho hoac bang bar
            if (totalPages <= ConstantClass.CommentBarStep)
            {
                ViewBag.BeginPage = 1;
                ViewBag.EndPage = totalPages;
            }
            else if (currentPageIndex <= ConstantClass.CommentBarStep / 2 + 1)
            {
                ViewBag.BeginPage = 1;
                ViewBag.EndPage = ConstantClass.CommentBarStep;
            }
            else if (currentPageIndex > totalPages - ConstantClass.CommentBarStep)
            {
                ViewBag.BeginPage = totalPages - ConstantClass.CommentBarStep;
                ViewBag.EndPage = totalPages;
            }
            else
            {
                ViewBag.BeginPage = currentPageIndex - ConstantClass.CommentBarStep / 2;
                ViewBag.EndPage = currentPageIndex + ConstantClass.CommentBarStep / 2;
            }


            //Kiem tra current page de cho xuat hien Previouspage hay khong
            if (currentPageIndex > ConstantClass.CommentBarStep / 2 + 1)
            {
                ViewBag.Previous_Mark_Visibility = true;
            }
            else
            {
                ViewBag.Previous_Mark_Visibility = false;
            }

            //Kiem tra current page de cho xuat hien Nextpage hay khong
            if (currentPageIndex <= totalPages - (ConstantClass.CommentBarStep / 2 + 1) && ViewBag.EndPage != totalPages)
            {
                ViewBag.Next_Mark_Visibility = true;
            }
            else
            {
                ViewBag.Next_Mark_Visibility = false;
            }


            if (totalPages <= ConstantClass.CommentBarStep)
            {
                ViewBag.Previous_Mark_Visibility = false;
                ViewBag.Next_Mark_Visibility = false;
            }

            ViewBag.NextPageIndex = Convert.ToInt16(currentPageIndex) + 1;
            ViewBag.PreviousPageIndex = Convert.ToInt16(currentPageIndex) - 1;
            ViewBag.CurrentPage = currentPageIndex;
            ViewBag.LastPage = totalPages;
            ////////////////////////// end paging
           
          
            ViewBag.CommentListOfArticle = DataSingleton.Instance.GetCommentModels()
                                          .GetCommentOfArticle_Frontend(articleID, currentPageIndex, ConstantClass.CommentPageStep);
            ViewBag.ArticleID = articleID;
            ViewBag.ArticleSeoUrl = currentArticle.ArticleSeoUrl;
            ViewBag.ArticleTypeID = DataSingleton.Instance.GetArticleModels().GetArticleTypeOfArticle(articleID);

            ViewBag.Title = currentArticle.Title;
            ViewBag.MetaDescription = currentArticle.Description;
            ViewBag.MetaArticleThumbnailUrl = currentArticle.Photo;

            IEnumerable<Article_Tag> listTag = DataSingleton.Instance.GetLinQContext().Article_Tags.Where(u => u.ArticleID == articleID);

            string metaTagList = "";
            foreach (var item in listTag)
            {
                if (item == listTag.Last())
                {
                    metaTagList += item.Tag.TagName;
                }
                else
                {
                    metaTagList += item.Tag.TagName + ",";
                }
            }

            ViewBag.MetaTagList = metaTagList;



            return View("/Views/FrontEnd/Article/ArticleDetail.cshtml");
        }




        /// <summary>
        /// Test new Singleton
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Test_New_Singleton(int id)
        {
            try
            {

                DataSingleton.Instance.GetLinQContext().Connection.Open();
                string a = DataSingleton.Instance.GetLinQContext().Connection.State.ToString();
                Article art = DataSingleton.Instance.GetLinQContext().Articles.SingleOrDefault(c => c.ArticleID == id);
                art.ViewNumber = art.ViewNumber + 1;
                string b = DataSingleton.Instance.GetLinQContext().Connection.State.ToString();
                DataSingleton.Instance.GetLinQContext().Articles.Context.SubmitChanges();

                DataSingleton.Instance.GetLinQContext().Connection.Close();
                string d = DataSingleton.Instance.GetLinQContext().Connection.State.ToString();
            }
            catch (Exception)
            {
                DataSingleton.Instance.GetLinQContext().Connection.Close();
                DataSingleton.Instance.RefreshInstance();
            }

            return View("/Views/FrontEnd/Test_New_Singleton.cshtml", DataSingleton.Instance.GetLinQContext().Articles.SingleOrDefault(c => c.ArticleID == id));
        }
        
        #endregion
    }
}
